from datetime import datetime
from datetime import timedelta
import re

from google.appengine.api import mail
from google.appengine.api import users


class Util:
    @staticmethod
    def getCurrentUser():
        user = users.get_current_user()
        if user:
            email = user.email()
            return email[:email.index("@")]
        return None

    @staticmethod
    def getLoginDetails():
        user = users.get_current_user()
        admin = 0
        username = ""
        loggedIn = 0
        email = ""
        if user:
            url = users.create_logout_url("/")
            email = user.email()
            username = email[:email.index("@")]
            url_text = 'Logout'
            loggedIn = 1
            if email == 'simon@ndunda.com' or email == 'simonndunda@gmail.com':
		admin = 1
		username = username + " (admin)"
        else:
            url = users.create_login_url("/login")
            url_text = 'Login'
	      
        return {"url":url, "username":username, "url_text":url_text, 'loggedIn':loggedIn, 'admin':admin, 'email':email}

    @staticmethod
    def login(self, callback):
	url = users.create_login_url("/login?callback=" + callback)
	self.redirect(url)
	
    @staticmethod
    def sendEmail(source, title, htmlMsg):
	htmlMsg = "<p><b>Kaa ni ka Email automated from cropdiagnosis.appspot.com after a comment from: <i>" + source + "</i></b></p>\n" + htmlMsg
	message = re.sub(r'<[^>]*?>', '', htmlMsg).replace("&nbsp;", " ")
        #overwrite the real source with an admin email adress (appengine emails can ony oiginate from admins).
	source = 'simonndunda@gmail.com'
        recipient = "info@perationtech.com"
        try:
            message = mail.EmailMessage(sender=source,subject=title)
            message.to = recipient
            message.body = message
            message.html = htmlMsg
            message.send()
            msg.response = "Success"
        except:
            msg.response = "Failed"
        msg.put()

    @staticmethod
    def handleTime(datetime):
        kenyantime = timedelta(hours=3)
        return (datetime + kenyantime).strftime("%d-%b-%Y")

    @staticmethod
    def handleTimeDetailed(datetime):
        kenyantime = timedelta(hours=3)
        return (datetime + kenyantime).strftime("%A, %B %d, %Y %I:%M %p")

    @staticmethod
    def isLoggedIn():
        user = users.get_current_user()
        if user:
            return True
        return False

    @staticmethod
    def now():
        return datetime.now()

